package com.morgan.storageperlib.saf.handler

import android.content.Intent
import android.net.Uri
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.documentfile.provider.DocumentFile

/**
 *description：创建文件夹 和 文件，在用户选择的文件夹下面 再创建 relativeDir 再创建 fileName 文件
             relativeDir:在用户选择的文件夹下面 再创建 的目录(以/分割)，可以为null
            imeiType:如"text/plain"
            fileName:文件名
 *<br>author：caowugao
 *<br>time：2021/3/5 0005 18:44
 */
open class CreateFileHandler(relativeDir : String? = null, imeiType : String, fileName : String, act : AppCompatActivity, contract : ActivityResultContract<Intent, ActivityResult> = ActivityResultContracts.StartActivityForResult(), callback : (Boolean, DocumentFile?, Uri?) -> Unit) : CreateFolderHandler(if (relativeDir != null && relativeDir.contains("/")) relativeDir.split("/")[0] else null, act, contract, { success, doc ->
    if (!success) {
        callback.invoke(success, doc, null)
    } else {
        try {
            var realDoc = doc!!
            if (relativeDir != null && relativeDir.contains("/")) {
                val splitDirs = relativeDir.split("/")
                if (splitDirs.size > 1) {
                    val rang = 1 until splitDirs.size
                    for (i in rang) {
                        realDoc = realDoc.createDirectory(splitDirs[i])!!
                    }
                }
            }
            realDoc.createFile(imeiType, fileName)
            realDoc.findFile(fileName)?.let { resultDoc ->
                callback.invoke(true, resultDoc, resultDoc.uri)
            }
        } catch (e: Throwable) {
            e.printStackTrace()
            callback.invoke(false, null, null)
        }
    }
}) {
}